package org.john.auth.client.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.john.auth.client.common.AuthClientConst;
import org.springframework.http.MediaType;

public class RequestUtil {

	private RequestUtil() {
		throw new IllegalStateException("Utility class");
	}

	private static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static String getSlbId(HttpServletRequest request) {
		String slbId = request.getHeader("SLB-ID");
		return StringUtils.isNotBlank(slbId) ? slbId : StringUtils.EMPTY;
	}

	public static String getClientPoint(HttpServletRequest request) {
		return getIpAddr(request);
	}

	public static String getServerPoint(HttpServletRequest request) {
		return (request.getLocalName() != null) ? request.getLocalName() : (request.getLocalAddr() != null) ? request.getLocalAddr() : StringUtils.EMPTY;
	}

	public static String getToken(HttpServletRequest request) {
		return request.getHeader(AuthClientConst.KEY_TOKEN_HEADER);
	}

	public static boolean isAjax(HttpServletRequest request) {
		return StringUtils.equals(request.getHeader("X-Requested-With"), "XMLHttpRequest");
	}

	public static boolean isRest(HttpServletRequest request) {
		return StringUtils.equals(request.getContentType(), MediaType.APPLICATION_JSON_VALUE);
	}
}